#!/bin/bash

if [ $# -lt 3 ]; then
  echo "Usage: $0 <path> <binaryname> <Gimbo-xml-path>"
  echo "Example: ./create_gdb_wrapper ../MuRo MuRo ../MuRo/MuRo.gconf"
  echo ""
  exit 0
fi

if [ ! -d $1 ]; then
  echo "Parameter '$1' was not a directory. Abort."
  exit 1
fi

if [ ! -f $3 ]; then
  echo "File \"${3}\" doesn't exists, cannot generate configuration, but continuing anyway."
else
  XMLCONF=${3}
fi

if [ ! -f ${1}/${2} ]; then
  echo "Warning: Binary file \"${1}/${2}\" doesn't exists, but continuing anyway."
fi 


# Compile wrappers
make

# Copy wrapper code
WRAPPERNAME=${1}/${2}-gdbwrapper
WRAPPERCONFNAME=${1}/${2}-gdbwrapper.conf
echo "Copy wrapper binary..."
cp -v gdbWrapper ${WRAPPERNAME}
echo "OK."
echo "Construct gdbWrapper conf..."
pushd $1
BINBATH="$(pwd)"
popd
echo -e "${BINBATH}\n${2}\n" > ${WRAPPERCONFNAME}
echo "OK."


# Create XML
if [ ! -z "${XMLCONF}" ]; then
  echo "Constructing GDB target XML..."
  TARGETXML=${XMLCONF}-gdb.gconf
  cat ${XMLCONF} | \
      sed 's/<name>\(.*\)<\/name>/<name>\1 (GDB)<\/name>/' | \
      sed 's/<location>\(.*\)<\/location>/<location>\1-gdbwrapper<\/location>/' > \
      ${TARGETXML}
  echo "OK."
fi
